# -*- coding: utf-8 -*-
'''
Created on 2013-4-15

@author: chenkaode@baidu.com
'''
import sys,os,re,time
from constant.Constant import *

class PhoneUtil:
    
    @classmethod
    def rootAndRemount(self):
        os.system("adb root")
        time.sleep(3)
        os.system("adb remount")
        time.sleep(2)
    
    @classmethod
    def rebootDevice(self):
        self.rootAndRemount()
        cmd = "adb reboot"
        os.system(cmd)
        time.sleep(90)
        self.rootAndRemount()
        
    @classmethod
    def pressEnterKey(self):
        os.system("adb shell input keyevent 66")
    
    
    @classmethod
    def connectWifi(self):
        self.rootAndRemount()
        openWifiCmd = "adb shell svc wifi enable"
        CommonUtil.execWithoutRet(openWifiCmd)
        pullCmd = "adb pull " + Constant.WIFI_INFO_FILE + Constant.TEMP_DIR + os.sep + "wpa_supplicant.conf"
        
        CommonUtil.execWithoutRet(pullCmd)
        fd = open(Constant.TEMP_DIR + os.sep + "wpa_supplicant.conf",'r')
        txt = fd.read()
        fd.close()
        pattern = "network=\{[\s\S]{8,20}Baidu_Wifi[\s\S]{20,100}\s\}"
        match = re.search(pattern,txt)
        if match == None:
            txt = txt + Constant.WIFI_CONFIG
        else:
            txt = txt[0:match.start()] + Constant.WIFI_CONFIG + txt[match.end():]
        fd = open(Constant.TEMP_DIR + os.sep + "wpa_supplicant.conf",'w')
        fd.write(txt)
        fd.close()
        pushCmd = "adb push " + Constant.TEMP_DIR\
                + os.sep + "wpa_supplicant.conf "\
                + Constant.WIFI_INFO_FILE
        CommonUtil.execWithoutRet(pushCmd)
        chownCmd = "adb shell chown system:wifi " + Constant.WIFI_INFO_FILE
        CommonUtil.execWithoutRet(chownCmd)
        closeWifiCmd = "adb shell svc wifi disable"
        CommonUtil.execWithoutRet(closeWifiCmd)
        CommonUtil.execWithoutRet(openWifiCmd)
        
    
        